package com.ogawa.base.utils

import android.os.Handler
import android.os.HandlerThread
import android.os.Message
import android.util.Log
import com.blankj.utilcode.util.LogUtils
import java.util.*
import kotlin.math.abs

class MyDownTimer {
    @Volatile
    var curTime = 0L
    @Volatile
    var totalTime = 0L
    @Volatile
    var netTime = 0L
    private var intervalTime = 1000L
    var isStart = false
    var isPause = false

    var timer: Timer = Timer()

    var handler = Handler()
    var mThread = HandlerThread("MyDownTimer handler_thread");
    var listener : TimeListener ?= null

    fun setTime(totalTime: Long,isPause: Boolean){
        this.totalTime = totalTime
        this.netTime = totalTime
        this.isPause = isPause
        start()
    }
    fun start(){

        if (!isStart|| abs(netTime-curTime) >3*1000){
            curTime = netTime
            mThread.start()
            isStart = true
            handler = Handler(mThread.looper, object : Handler.Callback {
                override fun handleMessage(msg: Message?): Boolean {
                    LogUtils.e("setTime222isPause: ${isPause} : ===isautoProgram=${netTime}====${curTime}")

                    handler.sendEmptyMessageDelayed(0, intervalTime)
                    if (isPause) {
                        listener?.onInterval(curTime)
                        return false
                    }
                    curTime -= intervalTime

                    if (curTime > 0) {
                        listener?.onInterval(curTime)
                    } else{
                        curTime = 0
                        netTime = 0
                        listener?.onFinish()
                        isPause = false
                        cancel()
                    }
                    return false
                }
            })
            handler.sendEmptyMessage(0)
        }

    }
    fun finish() {
        curTime = 0
        netTime = 0
        listener?.onInterval(0)
        isPause = true
        cancel()
        LogUtils.e("isPause==2")
    }
    fun onlyShowTime(time:Long) {
        listener?.onInterval(time)

    }
    fun cancel(){
        if (isStart){
            isStart = false
            mThread.quit()
        }
    }

    fun pause() {
        listener?.onInterval(curTime)
        cancel()
        isPause = true
        LogUtils.e("isPause==3")
    }

    fun resume() {
        isPause = false
//        start()
    }

    interface TimeListener {
        fun onFinish()
        fun onInterval(remainTime: Long)
    }



}